package com.ghostwan.androears;

import java.util.ArrayList;

import com.ghostwan.androears.adapter.*;
import com.ghostwan.androears.customObject.Album;
import com.ghostwan.androears.customObject.Artist;
import com.ghostwan.androears.customObject.Song;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.provider.MediaStore.Audio.*;
import android.text.Layout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

public class AndroEars extends Activity
{

	protected final static String TAG = "AndroEars";

	protected final static int ARTIST_VIEW = 0;
	protected final static int ALBUM_VIEW = 1;
	protected final static int SONG_VIEW = 2;
	protected final static int PLAYER_VIEW = 3;
	protected final static int PLAYLIST_VIEW = 4;
	static final int ADD_SONG_ID = 0;
	static final int ADD_ARTIST_ID = 1;
	static final double ORIENTATION_SCALE = 0.2;
	static final int DIALOG_GAMEOVER_ID = 1;
	public int mCurrentView;

	public ListView mMainList;
	public ListView mPlayList;
	public ArtistAdapter mArtistAdapter;
	public AlbumAdapter mAlbumAdapter;
	public SongAdapter mSongAdapter;
	public PlayListAdapter mPlayListAdapter;
	public Artist mCurrentArtist;
	public Album mCurrentAlbum;
	public MusicPlayerInterface mPlayerService;
	public MusicPlayer mMusicPlayer;
	public View mMainView;
	public View mPlayListView;
	public LayoutInflater mInflater;
	public TextView mInformationView;
	public AndroEars me;
	public ImageButton mMusicPlayerButton;

	@Override
	public void onConfigurationChanged(Configuration newConfig)
	{
		super.onConfigurationChanged(newConfig);
		/*
		 * if(mCurrentView == PLAYER_VIEW) if(newConfig.orientation ==
		 * Configuration.ORIENTATION_LANDSCAPE) { this. } else {
		 * this.setContentView(R.layout.musicplayer_layout);
		 * displayMediaPlayer(); }
		 */

	}

	private ServiceConnection mConnection = new ServiceConnection()
	{
		public void onServiceConnected(ComponentName className, IBinder service)
		{
			mPlayerService = MusicPlayerInterface.Stub.asInterface((IBinder) service);

			mMusicPlayer = new MusicPlayer(me, mInflater.inflate(R.layout.musicplayer, null));

			mMainList.setOnItemClickListener(new OnItemClickListener()
			{

				public void onItemClick(AdapterView<?> av, View view, int index, long arg)
				{

					switch (mCurrentView)
					{
					case ARTIST_VIEW:
						mCurrentArtist = (Artist) av.getAdapter().getItem(index);
						displayAlbumList();
						break;

					case ALBUM_VIEW:
						mCurrentAlbum = (Album) av.getAdapter().getItem(index);
						displaySongList();
						break;

					case SONG_VIEW:
						try
						{
							mMusicPlayer.loadSongList(mPlayerService.addSongPlaylist((Song) av
									.getAdapter().getItem(index)));
						}
						catch (RemoteException e)
						{
							// TODO Auto-generated catch block
							Log.e(TAG, e.getMessage());
						}
						displayMediaPlayer();
						break;
					}
				}
			});
			mPlayList.setOnItemClickListener(new OnItemClickListener()
			{

				@Override
				public void onItemClick(AdapterView<?> av, View v, int index, long arg)
				{
					mMusicPlayer.loadSongList(index);
					displayMediaPlayer();
					
				}
				
			});
			/*
			 * mListView.setOnItemLongClickListener(new
			 * OnItemLongClickListener() {
			 * 
			 * @Override public boolean onItemLongClick(AdapterView<?> av, View
			 * view, int index, long arg) {
			 * 
			 * return true; } catch (RemoteException e) { Log.e(TAG,
			 * e.getMessage()); } break;
			 * 
			 * case PLAYLIST_VIEW: try {
			 * 
			 * return true; } catch (RemoteException e) { // TODO Auto-generated
			 * catch block e.printStackTrace(); } break;
			 * 
			 * 
			 * } return false; }
			 * 
			 * });
			 */

			((Button) mMainView.findViewById(R.id.displayArtistButton))
					.setOnClickListener(new OnClickListener()
					{

						@Override
						public void onClick(View v)
						{
							displayArtistList();
						}
					});

			((Button) mMainView.findViewById(R.id.displayAlbumButton))
					.setOnClickListener(new OnClickListener()
					{

						@Override
						public void onClick(View v)
						{
							displayAlbumList();
						}
					});

			((Button) mMainView.findViewById(R.id.displaySongButton))
					.setOnClickListener(new OnClickListener()
					{

						@Override
						public void onClick(View v)
						{
							displaySongList();

						}
					});
			((ImageButton) mPlayListView.findViewById(R.id.mediaPlayerButton))
					.setOnClickListener(new OnClickListener()
					{

						@Override
						public void onClick(View v)
						{
							displayMediaPlayer();
						}
					});

			((ImageButton) mPlayListView.findViewById(R.id.clearPlayList))
					.setOnClickListener(new OnClickListener()
					{

						@Override
						public void onClick(View v)
						{
							try
							{
								mMusicPlayer.stop();
								mMusicPlayer.mPlayerService.clearPlaylist();
							}
							catch (RemoteException e)
							{
								Log.e(TAG, e.getMessage());
							}
							displayArtistList();
							mMusicPlayerButton.setVisibility(View.INVISIBLE);
						}
					});
			mMusicPlayerButton.setOnClickListener(new OnClickListener()
			{

				@Override
				public void onClick(View v)
				{
					displayMediaPlayer();
				}
			});

			displayArtistList();
		}

		public void onServiceDisconnected(ComponentName className)
		{
			mPlayerService = null;
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		mInflater = this.getLayoutInflater();
		mMainView = mInflater.inflate(R.layout.main, null);
		mPlayListView = mInflater.inflate(R.layout.playlist, null);
		me = this;
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		mMainList = (ListView) mMainView.findViewById(R.id.list);
		mMainList.setItemsCanFocus(true);
		mPlayList = (ListView) mPlayListView.findViewById(R.id.list);
		mPlayList.setItemsCanFocus(true);
		mInformationView = (TextView) mMainView.findViewById(R.id.infoView);
		mArtistAdapter = new ArtistAdapter(this, R.layout.artist_layout);
		mAlbumAdapter = new AlbumAdapter(this, R.layout.album_layout);
		mSongAdapter = new SongAdapter(this, R.layout.song_layout);
		mPlayListAdapter = new PlayListAdapter(this, R.layout.playlist_layout);
		mPlayList.setAdapter(mPlayListAdapter);
		mMusicPlayerButton = (ImageButton) mMainView.findViewById(R.id.mediaPlayerButton);
		mMusicPlayerButton.setVisibility(View.INVISIBLE);
		

		this.bindService(new Intent(AndroEars.this, MusicPlayerService.class), mConnection,
			Context.BIND_AUTO_CREATE);

	}

	@Override
	protected void onDestroy()
	{
		super.onDestroy();

		this.unbindService(mConnection);
	}

	@Override
	public void onResume()
	{
		super.onResume();

		registerReceiver(receiver, new IntentFilter(MusicPlayerService.BROADCAST_ACTION));
	}

	@Override
	public void onPause()
	{
		super.onPause();

		unregisterReceiver(receiver);
	}

	public ArrayList<Artist> getArtistsList()
	{
		ArrayList<Artist> artistList = new ArrayList<Artist>();

		// Form an array specifying which columns to return.
		String[] projection = new String[]
		{ Artists.ARTIST, Artists.ARTIST_KEY, Artists.NUMBER_OF_ALBUMS };

		// Get the base URI for the People table in the Contacts content
		// provider.
		Uri uri = Artists.EXTERNAL_CONTENT_URI;

		// Make the query.
		Cursor cursor = managedQuery(uri, projection, // Which columns to return
			null, // Which rows to return (all rows)
			null, // Selection arguments (none)
			// Put the results in ascending order by name
			null);

		if (cursor.moveToFirst())
		{

			do
			{
				// Get the field values
				Artist artist = new Artist(cursor.getString(cursor.getColumnIndex(Artists.ARTIST)),
						cursor.getString(cursor.getColumnIndex(Artists.ARTIST_KEY)));
				artist.mAlbumCount = cursor.getInt(cursor.getColumnIndex(Artists.NUMBER_OF_ALBUMS));
				artistList.add(artist);

			} while (cursor.moveToNext());

		}
		return artistList;
	}

	public ArrayList<Album> getAlbumList(Artist artist)
	{
		ArrayList<Album> albumList = new ArrayList<Album>();
		String selection = null;
		// Get the base URI for the People table in the Contacts content
		// provider.
		Uri uri = Albums.EXTERNAL_CONTENT_URI;

		// Form an array specifying which columns to return.
		String[] projection = new String[]
		{ Albums.ALBUM, Albums.ALBUM_KEY, Albums.NUMBER_OF_SONGS, Albums.ALBUM_ART,
				Artists.ARTIST_KEY, Albums.ALBUM_ART };

		if (artist != null)
		{
			mInformationView.setText("Artist: " + artist.mName);
			selection = Artists.ARTIST_KEY + "= '" + artist.mKey + "'";
		}
		else
		{
			mInformationView.setText("All artist");
		}
		// Make the query.
		Cursor cursor = managedQuery(uri, projection, selection,// Audio.keyFor(Albums.ARTIST)+"="+artistKey,
			null, null);
		Album album;

		if (cursor.moveToFirst())
		{

			do
			{
				album = new Album(cursor.getString(cursor.getColumnIndex(Albums.ALBUM)), cursor
						.getString(cursor.getColumnIndex(Albums.ALBUM_KEY)));
				album.mSongCount = cursor.getInt(cursor.getColumnIndex(Albums.NUMBER_OF_SONGS));
				album.mAlbumCover = cursor.getString(cursor.getColumnIndex(Albums.ALBUM_ART));
				albumList.add(album);

			} while (cursor.moveToNext());

		}
		return albumList;
	}

	public ArrayList<Song> getSongList(Artist artist, Album album)
	{
		ArrayList<Song> songList = new ArrayList<Song>();
		String selection = "";
		String title = "";
		Cursor songCursor;
		// Cursor albumCursor;
		Uri uri = Media.EXTERNAL_CONTENT_URI;
		// Uri uri2 =
		// android.provider.MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;

		String[] projectionSong = new String[]
		{ Media.TITLE, Media.DURATION, Media.TITLE_KEY, Media.DATA, Media.ARTIST, Media.ARTIST_KEY,
				Media.ALBUM, Media.ALBUM_KEY };

		// String[] projectionAlbum = new String[]
		// {Albums.ALBUM_ART,Albums.ALBUM_KEY};

		if (artist != null)
		{
			mInformationView.setText("Artist: " + artist.mName);
			selection += Media.ARTIST_KEY + " = '" + artist.mKey + "'";
			title += artist.mName;
		}

		if (artist != null && album != null)
		{
			selection += " AND ";
			title += " : ";
		}

		if (album != null)
		{
			mInformationView.setText("Album: " + album.mName);
			selection += Media.ALBUM_KEY + " = '" + album.mKey + "'";
			title += album.mName;

		}
		if (artist == null && album == null) selection = null;

		// Make the query.
		songCursor = managedQuery(uri, projectionSong, selection, null, null);

		if (songCursor.moveToFirst())
		{

			do
			{
				Song song = new Song(songCursor.getString(songCursor.getColumnIndex(Media.TITLE)),
						songCursor.getString(songCursor.getColumnIndex(Media.TITLE_KEY)));
				song.mDuration = songCursor.getInt(songCursor.getColumnIndex(Media.DURATION));

				song.mArtistName = songCursor.getString(songCursor.getColumnIndex(Media.ARTIST));
				song.mArtistKey = songCursor.getString(songCursor.getColumnIndex(Media.ARTIST_KEY));
				song.mAlbumName = songCursor.getString(songCursor.getColumnIndex(Media.ALBUM));
				song.mAlbumKey = songCursor.getString(songCursor.getColumnIndex(Media.ALBUM_KEY));

				if (album != null)
					song.mSongCover = album.mAlbumCover;
				else
					song.mSongCover = null;

				song.mPath = songCursor.getString(songCursor.getColumnIndex(Media.DATA));
				songList.add(song);

			} while (songCursor.moveToNext());

		}
		return songList;
	}

	public void displayArtistList()
	{
		mCurrentView = ARTIST_VIEW;
		mCurrentArtist = null;
		mCurrentAlbum = null;
		ArrayList<Artist> artistList = getArtistsList();
		setContentView(mMainView);
		if (artistList.size() > 0)
		{
			mInformationView.setText("Andro's ears:" + getString(R.string.sdcard_library));
			mArtistAdapter.setArtistList(artistList);
			mMainList.setAdapter(mArtistAdapter);
		}
		else
		{
			mInformationView.setText(getString(R.string.empty_song));
		}

	}

	public void displayAlbumList()
	{
		mCurrentView = ALBUM_VIEW;
		mCurrentAlbum = null;
		ArrayList<Album> albumList = getAlbumList(mCurrentArtist);
		setContentView(mMainView);

		if (albumList.size() == 1)
		{
			mCurrentAlbum = albumList.get(0);
			mInformationView.setText(getString(R.string.album) + ": " + mCurrentAlbum.mName);
			displaySongList();
		}
		else
		{
			mAlbumAdapter.setAlbumList(albumList);
			mMainList.setAdapter(mAlbumAdapter);
		}

	}

	public void displaySongList()
	{
		mCurrentView = SONG_VIEW;
		ArrayList<Song> songList = getSongList(mCurrentArtist, mCurrentAlbum);
		mSongAdapter.setSongList(songList);
		mMainList.setAdapter(mSongAdapter);
	}

	public void displayPlayList()
	{
		setContentView(mPlayListView);
		mInformationView.setText(getString(R.string.current_list));
		mCurrentView = PLAYLIST_VIEW;

		try
		{
			mPlayListAdapter.setSongList((ArrayList<Song>) mPlayerService.getSongList());
		}
		catch (RemoteException e)
		{
			Log.e(TAG, e.getMessage());
		}
	}

	public void displayMediaPlayer()
	{
		mMusicPlayerButton.setVisibility(View.VISIBLE);
		mCurrentView = PLAYER_VIEW;
		setContentView(mMusicPlayer.mView);
		try
		{
			mMusicPlayer.play();
		}
		catch (RemoteException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			switch (mCurrentView)
			{
			case ALBUM_VIEW:
				displayArtistList();
				return true;

			case SONG_VIEW:
				if (mCurrentArtist != null && mCurrentArtist.mAlbumCount == 1)
					displayArtistList();
				else
					displayAlbumList();
				return true;

			case PLAYER_VIEW:
				if (mCurrentAlbum != null)
					displaySongList();
				else
					displayArtistList();
				return true;

			case PLAYLIST_VIEW:
				displayMediaPlayer();
				mCurrentView = PLAYER_VIEW;
				return true;

			}
			return super.onKeyDown(keyCode, event);
		}
		return false;
	}

	private BroadcastReceiver receiver = new BroadcastReceiver()
	{
		public void onReceive(Context context, Intent intent)
		{
			String event = intent.getStringExtra("com.ghostwan.androears.MusicPLayerAction");
			if (event.equals("next") || event.equals("previous"))
			{
				try
				{
					mMusicPlayer.prepareSongPlaying(mMusicPlayer.mPlayerService.getCurrentSong());
					mPlayListAdapter.notifyDataSetChanged();
				}
				catch (RemoteException e)
				{
					// TODO Auto-generated catch block
					Log.e(TAG, "error BroadcastReceiver: " + e.getMessage());
				}
				;
			}
		}
	};
}